package com.ruoyi.car.controller;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.car.domain.PayRecord;
import com.ruoyi.car.domain.PurchaseOrder;
import com.ruoyi.car.service.IPayRecordService;
import com.ruoyi.car.service.IPurchaseOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 支付记录（支付页、支付成功页）Controller
 * 
 * @author yby
 * @date 2025-09-01
 */
@RestController
@RequestMapping("/car/pay")
public class PayRecordController extends BaseController
{
    @Autowired
    private IPayRecordService payRecordService;
    
    @Autowired
    private IPurchaseOrderService purchaseOrderService;

    /**
     * 查询支付记录（支付页、支付成功页）列表
     */
    @PreAuthorize("@ss.hasPermi('car:pay:list')")
    @GetMapping("/list")
    public TableDataInfo list(PayRecord payRecord)
    {
        startPage();
        List<PayRecord> list = payRecordService.selectPayRecordList(payRecord);
        return getDataTable(list);
    }

    /**
     * 导出支付记录（支付页、支付成功页）列表
     */
    @PreAuthorize("@ss.hasPermi('car:pay:export')")
    @Log(title = "支付记录（支付页、支付成功页）", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PayRecord payRecord)
    {
        List<PayRecord> list = payRecordService.selectPayRecordList(payRecord);
        ExcelUtil<PayRecord> util = new ExcelUtil<PayRecord>(PayRecord.class);
        util.exportExcel(response, list, "支付记录（支付页、支付成功页）数据");
    }

    /**
     * 获取支付记录（支付页、支付成功页）详细信息
     */
    @PreAuthorize("@ss.hasPermi('car:pay:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(payRecordService.selectPayRecordById(id));
    }

    /**
     * 生成支付流水号
     */
    @PreAuthorize("@ss.hasPermi('car:pay:add')")
    @GetMapping("/generateTradeNo")
    public AjaxResult generateTradeNo()
    {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomNum = String.format("%06d", new Random().nextInt(1000000));
        String tradeNo = "PAY" + timestamp + randomNum;
        return success(tradeNo);
    }
    
    /**
     * 获取订单列表（用于下拉选择）
     */
    @PreAuthorize("@ss.hasPermi('car:pay:list')")
    @GetMapping("/getOrderList")
    public AjaxResult getOrderList()
    {
        List<PurchaseOrder> list = purchaseOrderService.selectPurchaseOrderList(new PurchaseOrder());
        return success(list);
    }
    
    /**
     * 获取支付表单初始化数据
     */
    @PreAuthorize("@ss.hasPermi('car:pay:list')")
    @GetMapping("/getFormData")
    public AjaxResult getFormData()
    {
        Map<String, Object> data = new HashMap<>();
        
        // 生成支付流水号
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomNum = String.format("%06d", new Random().nextInt(1000000));
        String tradeNo = "PAY" + timestamp + randomNum;
        data.put("tradeNo", tradeNo);
        
        // 获取订单列表
        List<PurchaseOrder> orderList = purchaseOrderService.selectPurchaseOrderList(new PurchaseOrder());
        data.put("orderList", orderList);
        
        // 支付方式选项
        Map<String, String> payTypeOptions = new HashMap<>();
        payTypeOptions.put("wechat", "微信支付");
        payTypeOptions.put("alipay", "支付宝");
        payTypeOptions.put("unionpay", "银联支付");
        data.put("payTypeOptions", payTypeOptions);
        
        // 支付状态选项
        Map<String, String> payStatusOptions = new HashMap<>();
        payStatusOptions.put("0", "待支付");
        payStatusOptions.put("1", "支付成功");
        payStatusOptions.put("2", "支付失败");
        data.put("payStatusOptions", payStatusOptions);
        
        return success(data);
    }

    /**
     * 新增支付记录（支付页、支付成功页）
     */
    @PreAuthorize("@ss.hasPermi('car:pay:add')")
    @Log(title = "支付记录（支付页、支付成功页）", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PayRecord payRecord)
    {
        // 如果流水号为空，自动生成
        if (payRecord.getTradeNo() == null || payRecord.getTradeNo().trim().isEmpty()) {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String randomNum = String.format("%06d", new Random().nextInt(1000000));
            payRecord.setTradeNo("PAY" + timestamp + randomNum);
        }
        
        return toAjax(payRecordService.insertPayRecord(payRecord));
    }

    /**
     * 修改支付记录（支付页、支付成功页）
     */
    @PreAuthorize("@ss.hasPermi('car:pay:edit')")
    @Log(title = "支付记录（支付页、支付成功页）", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PayRecord payRecord)
    {
        return toAjax(payRecordService.updatePayRecord(payRecord));
    }

    /**
     * 删除支付记录（支付页、支付成功页）
     */
    @PreAuthorize("@ss.hasPermi('car:pay:remove')")
    @Log(title = "支付记录（支付页、支付成功页）", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(payRecordService.deletePayRecordByIds(ids));
    }
}
